﻿using GENERIC.DBProvider;
using GENERIC.NHRepository.Interfaces;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GENERIC.NHRepository
{
    class SessionFactory
    {
        private static ISessionFactory BuildSessionFactory(string connectionString, string providerName)
        {
            var mapper = new ModelMapper();


            foreach (var map in typeof(IClassMap).Assembly
                                        .GetTypes()
                                        .Where(t =>
                                            t.IsClass &&
                                            !t.IsAbstract &&
                                            typeof(IClassMap).IsAssignableFrom(t))
                                        .Select(Activator.CreateInstance)
                                        .OfType<IClassMap>())
            {
                map.Map(mapper);
            }

            var cfg = new Configuration();

            cfg.DataBaseIntegration(c =>
            {
                c.ConnectionString = connectionString;
                var dbType = DbUtils.GetConnectionType(providerName);
                if (dbType == eConnectionType.SqlCE)
                {
                    c.Driver<SqlServerCeDriver>();
                    c.Dialect<MsSqlCe40Dialect>();
                }
                else if(dbType== eConnectionType.SQLServer)
                {
                    c.Driver<SqlClientDriver>();
                    c.Dialect<MsSql2008Dialect>();
                }
                else
                {
                    throw new NotImplementedException();
                }

                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.SchemaAction = SchemaAutoAction.Create;
            });

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

            return cfg.BuildSessionFactory();
        }
    }
}
